package tests

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"restaurant-system/config"
	"restaurant-system/internal/models"
	"restaurant-system/routes"

	"github.com/gin-gonic/gin"
)

var router *gin.Engine

// 初始化测试环境
func SetupTestEnv() {
	// 设置为测试模式
	gin.SetMode(gin.TestMode)

	// 初始化数据库连接（使用测试数据库）
	config.InitTestDB()

	// 执行数据库迁移
	models.AutoMigrate()

	// 设置路由
	router = gin.New()
	routes.InitRoutes(router)
}

// 清理测试数据
func CleanTestData() {
	// 按照外键依赖的反序清理数据
	config.DB.Exec("SET FOREIGN_KEY_CHECKS = 0")

	// 清理所有表数据
	config.DB.Exec("DELETE FROM deliveries")
	config.DB.Exec("DELETE FROM delivery_addresses")
	config.DB.Exec("DELETE FROM stores")
	config.DB.Exec("DELETE FROM refunds")
	config.DB.Exec("DELETE FROM payments")
	config.DB.Exec("DELETE FROM table_reservations")
	config.DB.Exec("DELETE FROM tables")
	config.DB.Exec("DELETE FROM cart_items")
	config.DB.Exec("DELETE FROM user_coupons")
	config.DB.Exec("DELETE FROM coupon_templates")
	config.DB.Exec("DELETE FROM point_records")
	config.DB.Exec("DELETE FROM point_rules")
	config.DB.Exec("DELETE FROM reviews")
	config.DB.Exec("DELETE FROM order_items")
	config.DB.Exec("DELETE FROM orders")
	config.DB.Exec("DELETE FROM dishes")
	config.DB.Exec("DELETE FROM users")
	config.DB.Exec("DELETE FROM order_stats")
	config.DB.Exec("DELETE FROM browsing_histories")
	config.DB.Exec("DELETE FROM user_favorites")
	config.DB.Exec("DELETE FROM user_preferences")

	config.DB.Exec("SET FOREIGN_KEY_CHECKS = 1")
}

// 创建测试请求
func MakeRequest(method, url string, body interface{}, token string) *httptest.ResponseRecorder {
	var reqBody []byte
	if body != nil {
		reqBody, _ = json.Marshal(body)
	}

	w := httptest.NewRecorder()
	req, _ := http.NewRequest(method, url, bytes.NewBuffer(reqBody))
	req.Header.Set("Content-Type", "application/json")
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}

	router.ServeHTTP(w, req)
	return w
}
